import React, { useEffect, useState } from "react";
import "./Line.css";
import {
  message, Spin, Empty,
  Table, Button, Space,
  Drawer, Form, Input,
  Select,
} from 'antd';
import { 
  giveRequest,
  getlineinfo,
  getstationinfo,
  addline,
  addstationinline,
  deleteline,
  deletestationinline,
  modifylineinfo,
} from "../../../lib/apiconfig";

const { Column } = Table;
const { Option } = Select;

/**
 * @description 关于站点的管理组件
 */
const Line = () => {
  const [data, setData] = useState(undefined);
  const [stationData, setStationData] = useState(undefined);
  const [drawer, setDrawer] = useState(false);
  const [freshAction, setFreshAction] = useState(false);
  const [title, setTitle] = useState("新增路线");
  const [currentMsg, setCurrentMsg] = useState({ name: "" });
  const [form] = Form.useForm();


  useEffect(() => {
    giveRequest(getlineinfo(0, 1000), "GET", null, res => {
      const status = res.status;
      if ( status === "fail" ) {
        message.error("获取数据失败");
        setData(null);
      } else {
        res.data.forEach(item => {
          item.station.forEach(st => {
            st["key"] = item.id + "lineinfo" + st.stationid;
          });
        });
        setData(res.data);

        giveRequest(getstationinfo(0, 1000), "GET", null, res => {
          const status = res.status;
          if ( status === "fail" ) {
            message.error("获取数据失败");
            setStationData(null);
          } else {
            res.data.forEach(item => {
              item["key"] = item.id + "stationinfo";
            });
            setStationData(res.data);
          }
        });
      }
    });
  }, [freshAction]);

  // 新增站点
  const newLine = () => {
    const message = { name: "" };
    setTitle("新增路线");
    setCurrentMsg(message);
    form.setFieldsValue(message);
    setDrawer(true);
  }

  // 修改站点信息
  const modifyLineInfo = (id, name) => {
    const message = { id: id, name: name };
    setTitle("修改路线信息");
    setCurrentMsg(message);
    form.setFieldsValue(message);
    setDrawer(true);
  };

  // 在路线上新增站点
  const newStationInLine = (lineid, sequence) => {
    const message = { stationid: "", lineid: lineid, sequence: sequence }
    setTitle("新增站点");
    setCurrentMsg(message);
    form.setFieldsValue(message);
    setDrawer(true);
  }

  // 删除站点
  const deleteLine = (id, name) => {
    giveRequest(
      deleteline,
      "POST",
      {
        status: "deleteline",
        data: {
          id: id,
          name: name,
        }
      },
      res => {
        const status = res.status;
        if ( status === "success" ) {
          message.success("删除成功");
          setFreshAction(!freshAction);
        } else {
          message.error("删除失败!");
        }
      }
    );
  };

  // 删除路线上的站点
  const deleteStationInLine = (stationid, lineid) => {
    giveRequest(
      deletestationinline,
      "POST",
      {
        status: "deletestationinline",
        data: {
          stationid: stationid,
          lineid: lineid
        }
      },
      res => {
        const status = res.status;
        if ( status === "success" ) {
          message.success("删除成功");
          setFreshAction(!freshAction);
        } else {
          message.error("删除失败!");
        }
      }
    );
  }
  
  // 提交表单
  const submit = () => {
    if ( title === "修改路线信息" && currentMsg && currentMsg.id && currentMsg.name ) {
      giveRequest(
        modifylineinfo,
        "POST",
        {
          status: "modifylineinfo",
          data: {
            id: currentMsg.id,
            name: currentMsg.name,
          }
        },
        res => {
          const status = res.status;
          if ( status === "success" ) {
            message.success("修改成功");
            setDrawer(false);
            setFreshAction(!freshAction);
          } else {
            message.error("修改失败!");
          }
        }
      );
    } else if ( title === "新增路线" && currentMsg && currentMsg.name ) {
      giveRequest(
        addline,
        "POST",
        {
          status: "addline",
          data: {
            name: currentMsg.name,
          }
        },
        res => {
          const status = res.status;
          if ( status === "fail" ) {
            message.error("添加失败!");
          } else if ( status === "warning" ) {
            message.warn("该路线已存在!");
          } else {
            message.success("添加成功");
            setDrawer(false);
            setFreshAction(!freshAction);
          }
        }
      );
    } else if ( title === "新增站点" && currentMsg && currentMsg.stationid && currentMsg.lineid && currentMsg.sequence) {
      giveRequest(
        addstationinline,
        "POST",
        {
          status: "addstationinline",
          data: {
            stationid: currentMsg.stationid,
            lineid: currentMsg.lineid,
            sequence: currentMsg.sequence
          }
        },
        res => {
          const status = res.status;
          if ( status === "fail" ) {
            message.error("添加失败!");
          } else if ( status === "warning" ) {
            message.warn("该站点已存在!");
          } else {
            message.success("添加成功");
            setDrawer(false);
            setFreshAction(!freshAction);
          }
        }
      );
    } else {
      message.warn("信息不能为空!");
    }
  };


  return (
    <div className="Line-page">
    { function() {
      if ( data === undefined )
        return (
          <div className="Line-loading flex-column-center-center">
            <Spin size="large" />
          </div>
        );
      else if ( data === null ) 
        return (
          <div className="Line-failed flex-column-center-center">
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
          </div>
        );
      else
        return (
          <div className="Line-content flex-column-center-center">
            <div className="Line-table">
            {data.map(line => {
              return (
                <div className="Line-a-table" key={line.id + "line"}>
                  <div className="Line-a-table-title flex-row-between-center">
                    <div style={{ marginLeft: "90px", fontSize: "30px" }}>{line.name}路</div>
                    <div style={{ marginRight: "25px" }}>
                      <Button type="link" style={{ padding: 0, marginRight: "20px" }} onClick={() => modifyLineInfo(line.id, line.name)}>
                        修改信息
                      </Button>
                      <Button type="link" style={{ padding: 0 }} onClick={() => deleteLine(line.id, line.name)}>
                        删除路线
                      </Button>
                    </div>
                  </div>
                  <Table 
                    dataSource={line.station} 
                    className="Line-a-table-table" 
                    pagination={{ 
                      pageSize: 5, 
                      style: { 
                        marginRight: "50%", 
                        transform: "translate(50%, 0)",
                        display: "flex",
                        flexDirection: "row",
                        justifyContent: "center",
                        alignItems: "center" 
                      } 
                    }}
                  >
                    <Column 
                      title="站点ID" 
                      dataIndex="stationid" 
                      key="stationid"  
                    />
                    <Column 
                      title="站点名称" 
                      dataIndex="stationname" 
                      key="stationname"
                      defaultSortOrder="descend"
                      sorter={(a, b) => b.sequence - a.sequence}
                    />
                    <Column
                      title="操作"
                      key="action"
                      render={record => (
                        <Space size="middle">
                          <Button 
                            type="link"
                            style={{ padding: 0 }}
                            onClick={() => {
                              newStationInLine(
                                line.id,
                                record.sequence ? 
                                (record.sequence + (record.index === 0 ? 0 : line.station[record.index-1].sequence)) / 2 :
                                1
                              );
                            }}
                          >
                            添加在前
                          </Button>
                          <Button 
                            type="link"
                            style={{ padding: 0 }}
                            onClick={() => {
                              newStationInLine(
                                line.id,
                                record.sequence ? 
                                (record.sequence + (record.index === line.station.length-1 ? record.sequence+2 : line.station[record.index+1].sequence)) / 2 :
                                1
                              );
                            }}
                          >
                            添加在后
                          </Button>
                          <Button 
                            type="link"
                            style={{ padding: 0 }}
                            onClick={() => deleteStationInLine(record.stationid, line.id)}
                          >
                            删除站点
                          </Button>
                        </Space>
                      )}
                    />
                  </Table>
                </div>
              );
            })}
            </div>
            <div className="Line-new-account flex-row-start-center">
              <Button 
                type="primary" 
                size="large" 
                style={{ width: 150 }}
                onClick = {() => newLine()}
              >
                新增路线
              </Button>
            </div>
            <Drawer
              title={title}
              width={360}
              onClose={() => setDrawer(false)}
              visible={drawer}
              footer={
                <div style={{ textAlign: 'right' }}>
                  <Button 
                    style={{ marginRight: 16, width: 80 }}
                    onClick={() => setDrawer(false)}
                  >
                    取消
                  </Button>
                  <Button 
                    type="primary"
                    style={{ width: 80 }}
                    onClick={submit}
                  >
                    提交
                  </Button>
                </div>
              }
            >
              <Form 
                layout="vertical" 
                hideRequiredMark
                form={form}
                onValuesChange={data => {
                  const new_data = JSON.parse(JSON.stringify(currentMsg));
                  Object.keys(data).forEach(item => {
                    new_data[item] = data[item];
                  });
                  setCurrentMsg(new_data);
                }}
              >
              {
                function() {
                  switch ( title ) {
                    case "修改路线信息":
                      return (
                      <>
                        <Form.Item label="路线ID" name="id" rules={[{ required: true, message: "路线ID不能为空!" }]}>
                          <Input disabled />
                        </Form.Item>
                        <Form.Item label="路线名称" name="name" rules={[{ required: true, message: "路线名称不能为空!" }]}>
                          <Input placeholder="请输入路线名称~" />
                        </Form.Item>
                      </>
                      );
                    case "新增路线":
                      return (
                      <>
                        <Form.Item label="路线名称" name="name" rules={[{ required: true, message: "路线名称不能为空!" }]}>
                          <Input placeholder="请输入路线名称~" />
                        </Form.Item>
                      </>
                      );
                    case "新增站点":
                      return (
                      <>
                        <Form.Item label="站点名称" name="stationid" rules={[{ required: true, message: "站点不能为空!" }]}>
                          <Select>
                            { function() {
                              if ( stationData ) {
                                return stationData.map(item => {
                                  return (
                                    <Option value={item.id} key={item.key}>{item.name}</Option>
                                  );
                                });
                              } else {
                                return null;
                              }
                            } ()}
                          </Select>
                        </Form.Item>
                      </>
                      );
                    default:
                      break;
                  }
                } ()
              }
              </Form>
            </Drawer>
          </div>
        );
    } ()}
    </div>
  );
}

export default Line;